<template>
  <div class="dynamic-page">
    <!-- 顶部导航 -->
    <van-tabs v-model:active="activeTab" @click-tab="handleTabChange" class="custom-nav-bar">
      <van-tab title="关注"></van-tab>
      <van-tab title="最新"></van-tab>
      <van-tab title="新评论"></van-tab>
      <van-tab title="精华"></van-tab>
    </van-tabs>

    <!-- 圈子分类 -->
    <div>
      <div v-if="showGrid" class="grid-container">
        <van-grid :column-num="5">
          <van-grid-item
              v-for="(item, index) in gridList"
              :key="index"
              :icon="item.icon"
              :text="item.text"
              @click="handleGridItemClick(index+1)"
          />
        </van-grid>
      </div>
    </div>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <!-- 动态列表 -->
      <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          class="list"
          @load="onLoad"
      >
        <div
            v-for="dynamic in dynamicList"
            :key="dynamic.id"
            class="dynamic-item"
            @click="showDynamicDetail(dynamic)"
        >
          <div class="header">
            <van-image
                round
                width="40"
                height="40"
                :src="dynamic.avatar"
            />
            <div class="user-info">
              <div class="username">{{ dynamic.nickname }}</div>
              <div class="time">{{ formatTime(dynamic.createTime) }} 第{{ dynamic.postCount }}贴</div>
            </div>
            <van-button
                v-if="!dynamic.isSelf"
                class="follow-button"
                size="mini"
                :type="dynamic.isFollowed ? 'default' : 'primary'"
                @click.stop="toggleFollow(dynamic)"
            >
              {{ dynamic.isFollowed ? '已关注' : '+ 关注' }}
            </van-button>
          </div>

          <div class="content">
            <div class="text" :class="{ 'collapsed': !dynamic.isExpanded }">
              {{ dynamic.content.slice(0, dynamic.isExpanded ? undefined : maxTextLength) }}
              <span v-if="dynamic.content.length > maxTextLength && !dynamic.isExpanded" @click.stop="toggleExpand(dynamic)">
                ...<span style="color: #ff4949">展开</span>
              </span>
              <span v-if="dynamic.content.length > maxTextLength && dynamic.isExpanded" @click.stop="toggleExpand(dynamic)">
                <span style="color: #ff4949">收起</span>
              </span>
            </div>
            <div class="media-list">
              <template v-for="(media, index) in dynamic.media" :key="index">
                <div v-if="isVideo(media.url)" class="video-wrapper" @click.stop="playVideo(media.url)" :style="{ width: getMediaWidth(dynamic.media.length) }">
                  <van-image
                      :width="getMediaWidth(dynamic.media.length)"
                      :height="getMediaWidth(dynamic.media.length)"
                      fit="cover"
                      :src="media.cover || '/video.png'"
                  />
                  <van-icon name="play-circle" class="play-icon" />
                </div>
                <van-image
                    v-else
                    :width="getMediaWidth(dynamic.media.length)"
                    :height="getMediaWidth(dynamic.media.length)"
                    :src="media.url"
                    @click.stop="previewMedia(media.url, dynamic.media.map(m => m.url))"
                />
              </template>
            </div>
          </div>

          <div class="footer">
            <van-tag plain type="primary" @click.stop="showGroupDetail(dynamic.groupId)"># {{dynamic.groupName}}</van-tag>
            <div class="actions">
              <div style="color: #666666">举报</div>
              <!-- 点赞 -->
              <div class="action-item" @click.stop="toggleLike(dynamic)">
                <van-icon
                    :name="dynamic.isLiked ? 'good-job' : 'good-job-o'"
                    :color="dynamic.isLiked ? '#ee0a24' : '#666'"
                />
                <span>{{ dynamic.likeCount }}</span>
              </div>

              <!-- 评论 -->
              <div class="action-item">
                <van-icon name="comment-o" />
                <span>{{ dynamic.commentCount }}</span>
              </div>

              <!-- 收藏 -->
              <div class="action-item" @click.stop="toggleFavorite(dynamic)">
                <van-icon
                    :name="dynamic.isFavorited ? 'star' : 'star-o'"
                    :color="dynamic.isFavorited ? '#ffd700' : '#666'"
                />
                <span>{{ dynamic.favoriteCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>

    <!-- 弹窗：用于视频预览 -->
    <van-popup v-model:show="videoPreviewVisible" position="center" round>
      <video
          :src="currentVideoUrl"
          controls
          autoplay
          style="width: 100%; max-width: 600px; height: auto;"
      ></video>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getDynamicList, followUser, likeDynamic, favoriteDynamic } from '@/api/index.js';
import dayjs from 'dayjs';
import { useUserInfoStore } from "@/stores/userInfo.js";
import { useRouter } from "vue-router";
import { showImagePreview } from 'vant';

const router = useRouter();
const userInfoStore = useUserInfoStore();
const activeTab = ref(1);
const dynamicList = ref([]);
const loading = ref(false);
const finished = ref(false);
const pageParams = ref({ current: 0, size: 5 });
const total = ref(0);
const showGrid = ref(false); // 控制圈子分类显示
const refreshing = ref(false); // 新增：下拉刷新状态
const maxTextLength = ref(20); // 设置最大显示字符数
// 新增视频封面缓存
const videoCovers = ref({});
// 当前播放的视频地址
const videoPreviewVisible = ref(false);
const currentVideoUrl = ref('');

onMounted(() => {
  if(localStorage.getItem('index')!=null){
    activeTab.value=parseInt(localStorage.getItem('index'))
  }
  if(activeTab.value==1){
    showGrid.value=true;
  }
})

const gridList = [
  { icon: '/大杂烩.png', text: '大杂烩'},
  { icon: '/有问必答.png', text: '有问必答'},
  { icon: '/与茶会友.png', text: '与茶会友'},
  { icon: '/随手拍.png', text: '随手拍'},
  { icon: '/教程攻略.png', text: '教程攻略'},
  { icon: '/全部圈子.png', text: '全部圈子'}
];

// 判断是否为图片
const isImage = (url) => {
  return /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(url);
};

// 判断是否为视频
const isVideo = (url) => {
  return /\.(mp4|avi|mov|wmv|flv|mkv)$/i.test(url);
};

// 获取视频封面方法
const getVideoCover = (url) => {
  return new Promise((resolve) => {
    if (videoCovers.value[url]) return resolve(videoCovers.value[url]);
    const video = document.createElement('video');
    video.crossOrigin = 'anonymous';
    video.muted = true;
    video.playsInline = true;
    video.src = url;
    video.addEventListener('loadeddata', () => {
      video.currentTime = 0.1;
    });
    video.addEventListener('seeked', () => {
      const canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      const dataUrl = canvas.toDataURL('image/jpeg');
      videoCovers.value[url] = dataUrl;
      resolve(dataUrl);
    });
    video.addEventListener('error', () => {
      resolve('/video.png');
    });
  });
};

// 图片预览
const previewMedia = (currentMedia, mediaList) => {
  showImagePreview({
    images: mediaList.filter(isImage),
    startPosition: mediaList.indexOf(currentMedia),
    closeable: true,
  });
};

// 播放视频
const playVideo = (videoUrl) => {
  currentVideoUrl.value = videoUrl;
  videoPreviewVisible.value = true;
};

// 加载动态列表
const loadDynamics = async () => {
  try {
    const res = await getDynamicList({
      tabType: activeTab.value + 1,
      ...pageParams.value,
    });
    const processedList = res.list.map(dynamic => ({
      ...dynamic,
      isSelf: dynamic.nickname === userInfoStore.nickname,
      isExpanded: false,
      media: (dynamic.images || []).map(url => ({
        url,
        type: isVideo(url) ? 'video' : 'image',
        cover: null
      }))
    }));
    // 异步加载视频封面
    for (const dynamic of processedList) {
      for (const media of dynamic.media) {
        if (media.type === 'video') {
          media.cover = await getVideoCover(media.url);
        }
      }
    }
    dynamicList.value = [...dynamicList.value, ...processedList];
    console.log(dynamicList.value)
    total.value = res.total;
    finished.value = pageParams.value.current * pageParams.value.size >= total.value;
  } catch (error) {
    console.error('加载动态失败:', error);
    finished.value = true;
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 展开/收起操作
const toggleExpand = (dynamic) => {
  dynamic.isExpanded = !dynamic.isExpanded;
};

// 无限加载处理
const onLoad = () => {
  pageParams.value.current++;
  loadDynamics();
};

// 下拉刷新处理
const onRefresh = () => {
  pageParams.value.current = 1;
  loadDynamics();
};

// 切换标签页
const handleTabChange = (clickedTab) => {
  dynamicList.value = [];
  pageParams.value.current = 1;
  switch (clickedTab.title){
    case '关注':
      showGrid.value = false;
      localStorage.setItem('index',0);
      break;
    case '最新':
      showGrid.value = true;
      localStorage.setItem('index',1);
      break;
    case '新评论':
      showGrid.value = false;
      localStorage.setItem('index',2);
      break;
    case '精华':
      showGrid.value = false;
      localStorage.setItem('index',3);
      break;
  }
  loadDynamics();
};

// 切换圈子
const handleGridItemClick = (groupId) => {
  if(groupId !=6) router.push(`/groupDetail/${groupId}`);
  else router.push('/findGroup');
};

// 关注操作
const toggleFollow = async (dynamic) => {
  try {
    await followUser(dynamic.creator);
    dynamic.isFollowed = !dynamic.isFollowed;
  } catch (error) {
    console.error('关注操作失败:', error);
  }
};

const showGroupDetail = (groupId) => {
  router.push(`/groupDetail/${groupId}`);
};

// 时间格式化
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm');
};

// 点赞操作
const toggleLike = async (dynamic) => {
  try {
    await likeDynamic(dynamic.id);
    dynamic.isLiked = !dynamic.isLiked;
    dynamic.likeCount += dynamic.isLiked ? 1 : -1;
  } catch (error) {
    console.error('操作失败:', error);
  }
};

// 收藏操作
const toggleFavorite = async (dynamic) => {
  try {
    await favoriteDynamic(dynamic.id);
    dynamic.isFavorited = !dynamic.isFavorited;
    dynamic.favoriteCount += dynamic.isFavorited ? 1 : -1;
  } catch (error) {
    console.error('操作失败:', error);
  }
};

const showDynamicDetail= (dynamic) => {
  localStorage.setItem('dynamic', JSON.stringify(dynamic))
  router.push(`/dynamicDetail/${dynamic.id}`);
};

// 计算媒体项宽度
const getMediaWidth = (count) => {
  if (count < 3) {
    return `calc(100% / ${count} - 5px)`;
  }
  return '105px';
};
</script>

<style scoped>
.video-wrapper {
  position: relative;
  display: inline-block;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 24px;
  color: rgba(255, 255, 255, 0.8);
  filter: drop-shadow(0 0 2px rgba(0, 0, 0, 0.5));
}

.media-list {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 10px;
}
/* 增加对van-tabs的深度选择器以覆盖默认样式 */
::v-deep .custom-nav-bar .van-tabs__nav {
  background-color: #f5f5f5; /* 更改为你想要的颜色 */
}
/* 使顶部导航栏固定在顶部 */
.custom-nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999; /* 确保它在其他内容之上 */
}

.grid-container{
  background-color: white;
  margin: 10px;
}
.dynamic-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-top: 46px; /* 同样需要设置padding-top来避免内容被固定的导航栏遮挡 */
}

.dynamic-item {
  margin: 10px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 15px;
}

.user-info {
  flex: 1;
}

.username {
  font-weight: 500;
  font-size: 14px;
}

.time {
  font-size: 12px;
  color: #666;
}

.footer {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.actions {
  margin-top: 10px;
  display: flex;
  gap: 20px;
  align-items: center;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 20px;
  color: #666;

  &:active {
    opacity: 0.6;
  }
}
.list{
  padding-bottom: 50px;
}
</style>
